<?php
/**
 * 客户端接口请求类
 *
 * 请妥善保存app_key和secret_key, 以免数据泄露
 *
 * @param string $app_key
 * @param string $secret_key
 */

namespace ChannelThrift\Service;

use Base\BaseService;
use \Common\Org\Xcrypt;
use \Services\AuctionService\InvalidException;

class AntNestService extends BaseService {

	/**
	 * @var 预定义变量
	 */
	protected   $m;

	/**
	 * @var 车商类型
	 */
	protected   $account_type = '';

	/**
	 * @var 蚁巢请求地址
	 */
	protected   $ant_url = '';
	/**
	 * @var 项目唯一标识
	 */
    private $_app_key =  'AK2016.API.1003';
	private $_access_token = '';
	/**
	 * @var 秘钥
	 */
	private $_secret_key = 'ax10ffer';



	public function __construct(){
		parent::__construct();
		$app_key    = C('APP_KEY');
		$secret_key = C('SECRET_KEY');
		if(empty($app_key)) $app_key = $this->_app_key;
		if(empty($secret_key)) $secret_key = $this->_secret_key;
		$m = new Xcrypt($secret_key, 'ecb', 'auto');
		$time_now = time();
		$access_key = $app_key . '_' . $secret_key . '_' . $time_now;
		$this->_app_key = $app_key;
		$this->_access_token = $m->encrypt($access_key, 'base64');
		$this->account_type = C('ACCOUNT_TYPE');
		$this->ant_url = C('ANT_URL');
	}

	/**
	 * 登录服务
	 * @param $city_code
	 */
	public function ant_login($userName='',$pwd=''){
		$option  = json_encode(array('account_type'=>$this->account_type,'user_name'=>$userName,'pwd'=>$pwd));
		$info = $this->juhecurl($this->ant_url.C('USE_ROUTE.login'),$option,1);
		$info = json_decode($info,true);
		if($info['code'] === "000000"){
			$result = array(
					'user_name'=>$info['data']['info']['account_name'],
					'uid'=>$info['data']['info']['account_id'],
					'sms_mobile'=>$info['data']['info']['mobile'],
					'email'=>$info['data']['info']['email'],
					'status'=>$info['data']['info']['status'],
					'code'=>$info['code']
			);
			return $result;
		}else{
			return $info;
		}
	}

	/**
	 * 获取公钥、秘钥
	 * @return bool|mixed|string
	 */
	public function get_rsakey($type){
		$info = $this->juhecurl($this->ant_url.C('USE_ROUTE.get_rsa_key'),json_encode(array('key_type'=>$type)));
		$info = json_decode($info,true);
		if($info['code'] === "000000"){
			return $info;
		}
		return false;
	}

	/**
	 * 修改用户信息
	 * @param array $data   用户信息  account_id 必须
	 * @return bool
	 */
	public  function set_user($data = array()){
		if(!isset($data['account_id'])) return false;

		foreach($data as $key=>$val){
			$option[$key] = $val;
		}
		$option['account_type'] =$this->account_type;
		$info = $this->juhecurl($this->ant_url.C('USE_ROUTE.change_info'),json_encode($option),1);
		$info = json_decode($info,true);
		if($info['code'] === "000000"){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 根据uid获取用户信息
	 * @param string $uid 用户id
	 * @return array
	 */
	public  function  get_userinfo($uid = ''){
		$option  = json_encode(array('account_type'=>$this->account_type,'account_id'=>$uid));
		$info = $this->juhecurl($this->ant_url.C('USE_ROUTE.get_info_by_uid'),$option);
		$info = json_decode($info,true);
		if($info['code'] === "000000"){
			$result = array(
					'user_name'=>$info['data']['account_name'],
					'uid'=>$info['data']['account_id'],
					'sms_mobile'=>$info['data']['mobile'],
					'nick_name'=>$info['data']['nick_name'],
					'real_name'=>$info['data']['real_name'],
					'avatar'=>$info['data']['account_avatar'],
					'status'=>$info['data']['status'],
					'createtime'=>$info['data']['reg_date'],
					'las_login_time'=>$info['data']['las_login_time'],
					'updatetime'=>$info['data']['last_modify_time'],
			);
			return $result;
		}
		return false;
	}


	/**
	 * 请求接口返回内容
	 *
	 * @param  string $url [请求的URL地址]
	 * @param  string $header [header权限校验参数]
	 * @param  json $params [请求的参数]
	 * @param  int $ipost [是否采用POST形式]
	 * @return  string
	 */
	public function juhecurl($url, $params='', $ispost=0){
		$httpInfo = array();
		$ch = curl_init();
		$header = array(
				"content-type: application/x-www-form-urlencoded; charset=UTF-8",
				'appkey:' . $this->_app_key,
				'token:' . $this->_access_token,
		);
		curl_setopt($ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
		curl_setopt($ch,CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
		curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
		curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER , true );
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt ($ch, CURLOPT_COOKIE, 'XDEBUG_SESSION=1');
		//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

		$params = json_decode($params, true);
		$data = http_build_query($params);
		/*备注： 如果后期需要对http通讯过程中的数据做加密传输，则打开以下代码*/
		// $m = new \Common\Org\Xcrypt($key, 'ecb', 'auto');
		// $data = $m->encrypt($a);
		if( $ispost )
		{
			curl_setopt( $ch , CURLOPT_POST , true );
			curl_setopt( $ch , CURLOPT_POSTFIELDS , $data );
			curl_setopt( $ch , CURLOPT_URL , $url );
		}
		else
		{
			$strUrl = !empty($data) ? $url.'?'.$data : $url;
			curl_setopt( $ch , CURLOPT_URL , $strUrl);
		}
		$response = curl_exec( $ch );
		if ($response === FALSE) {
            throw new InvalidException(array('code' => 130000, 'message' => $this->exceptionCode[130000]));
		}
		$httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
		$httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
		curl_close( $ch );
		return $response;
	}

    /**
     * jpush 推送信息
     * @param $mobile
     * @param $jpush_id
     * @param $jpush_type
     * @param $jpush_data
     * @param $jpush_content
     * @return array|bool
     */
    public function jpush_msg($mobile,$jpush_id,$jpush_type,$jpush_data,$jpush_content,$is_post=1){
        $option  = json_encode(array(
            'mobile'=>$mobile,
            'jpush_id'=>$jpush_id,
            'jpush_type'=>$jpush_type,
            'jpush_data'=>$jpush_data,
            'jpush_content'=>$jpush_content
        ));
        $info = $this->juhecurl($this->ant_url.C('USE_ROUTE.jspuh'),$option,$is_post);
        $info = json_decode($info,true);

        if($info['code'] === "000000"){
            return $info;
        }else{
            trace('[jpush]蚁巢返回'.var_export($info,true),'','ERR',true);
            return false;
        }
    }

	/**
	 * 添加订阅
	 * @param $account_id
	 * @param $order_id
	 * @param int $sub_type
	 * @return mixed
	 */
	public function subscribe($accountId, $orderId, $subType = 1,$is_post=1){
			$option  = json_encode(array(
				'account_id' => $accountId,
				'order_id' => $orderId,
				'sub_type' => $subType
			));
			$info = $this->juhecurl($this->ant_url.C('USE_ROUTE.subscribe'),$option,$is_post);
			$info = json_decode($info,true);
			if($info['code'] === "000000"){
				return $info;
			}else{
				trace('[添加订阅]蚁巢返回'.var_export($info,true),'','ERR',true);
				return false;
			}
	}

}